package com.example.demo.controller.common;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.example.demo.common.IdParam;
import com.example.demo.domain.entity.Notice;
import com.example.demo.domain.entity.ProblemFile;
import com.example.demo.dto.ProblemFileDto;
import com.example.demo.dto.ResponseDto;
import com.example.demo.enums.FileUseEnum;
import com.example.demo.service.NoticeService;
import com.example.demo.service.ProblemFileService;
import com.example.demo.utils.CopyUtil;
import com.example.demo.utils.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 上传图片
 */
@RestController
@RequestMapping("/common")
public class UploadController {

    @Value("${problemFile.dir}")
    private String FILE_DIRECTORY;

    @Value("${problemFile.domain}")
    private String FILE_DOMAIN;

    private static final Logger log = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private ProblemFileService problemFileService;
    @Resource
    private NoticeService noticeService;

    /**
     * 上传图片接口
     * @param file 图片
     * @param use （"V", "查看"),("G", "评测"),("RF", "读取文件中的内容后评测"),("EFF", "评测函数图形"),("EGF", "评测几何图形"),("ESC", "评测统计图形"),("NOTICE", "公告轮播图");
     * @param problemId 题目id
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    @ResponseBody
    public ResponseDto upload(@RequestParam MultipartFile file, String use, long problemId) throws IOException {

        log.info("Start Upload File...");

        //保存文件到本地
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String key = UuidUtil.getShortUuid();

        FileUseEnum fileUseEnum = FileUseEnum.getByCode(use);
        String relativeDirectory = fileUseEnum.name().toLowerCase();

        String fullPath = FILE_DIRECTORY + relativeDirectory + File.separator + key + "-" + fileName;
        String returnPath = FILE_DIRECTORY + relativeDirectory + "/" + key + "-" + fileName;
        File fileDir = new File(FILE_DIRECTORY + relativeDirectory);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File dest = new File(fullPath);
        file.transferTo(dest);

        log.info(dest.getAbsolutePath());

        ProblemFileDto problemFileDto = new ProblemFileDto();
        problemFileDto.setName(fileName);
        problemFileDto.setPath(returnPath);
        problemFileDto.setSize(Integer.valueOf(String.valueOf(file.getSize())));
        problemFileDto.setSuffix(suffix);
        problemFileDto.setUse(use);
        Date now = DateUtil.date();

        if (FileUseEnum.NOTICE.getCode().equalsIgnoreCase(use)){
            // 公告轮播图
//            problemFileDto.setId(UuidUtil.getShortUuid());
//            problemFileDto.setCreatedAt(now);
//            problemFileDto.setUpdatedAt(now);
//            Notice notice = BeanUtil.copyProperties(problemFileDto, Notice.class);
            Notice notice = new Notice();
            notice.setPath(problemFileDto.getPath());
            notice.setName(problemFileDto.getName());
            notice.setSuffix(problemFileDto.getSuffix());
            notice.setSize(problemFileDto.getSize());
            notice.setCreatedAt(now);
            notice.setUpdatedAt(now);
            noticeService.createNotice(notice);
        }else if(problemId != -1) {
            problemFileDto.setProblemId(problemId);
            problemFileDto.setId(UuidUtil.getShortUuid());
            problemFileDto.setCreatedAt(now);
            problemFileDto.setUpdatedAt(now);
            ProblemFile problemFile = CopyUtil.copy(problemFileDto, ProblemFile.class);
            problemFile.setPath(relativeDirectory + File.separator + key + "-" + fileName);
            problemFileService.createProblemFile(problemFile);
        }

        ResponseDto<Object> responseDto = new ResponseDto<>();
        responseDto.setContent(problemFileDto);
        log.info(String.valueOf(responseDto));
        return responseDto;
    }

    /**
     * 通过id删除题目文件
     * @param id 文件id
     * @param use （"V", "查看"),("G", "评测"),("RF", "读取文件中的内容后评测"),("EFF", "评测函数图形"),("EGF", "评测几何图形"),("ESC", "评测统计图形"),("NOTICE", "公告轮播图");
     * @return
     */
    @RequestMapping("/deleteFileById")
    @ResponseBody
    public ResponseDto deleteFileById(@RequestParam(value="id") String id,
                                      @RequestParam(value="use") String use) {
        ResponseDto responseDto = new ResponseDto();
        int result = 0;
        if (FileUseEnum.NOTICE.getCode().equalsIgnoreCase(use)){
            result = noticeService.deleteFileById(id);
        }else{
            result = problemFileService.deleteProblemFileById(id);
        }
        if(result == 0) {
            responseDto.setSuccess(false);
        }
        return responseDto;
    }

    /**
     * 通过题目id找题目文件
     *
     * @param id
     * @return
     */
    @RequestMapping("/getProblemFileByProblemId")
    @ResponseBody
    public ResponseDto<List<ProblemFile>> getProblemFileByProblemId(@RequestBody IdParam id) {
        ResponseDto<List<ProblemFile>> result = new ResponseDto().buildSucceed();
        List<ProblemFile> data = problemFileService.getProblemFileByProblemId(id.getId());
        result.setContent(data);
        return result;
    }
}
